package com.grj.park.boot.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.grj.park.boot.domain.DeviceType;
import com.grj.park.boot.domain.R;
import com.grj.park.boot.service.DeviceTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.List;

import static cn.hutool.json.JSONUtil.toBean;

@Api(tags = "设备类型管理")
@RequiredArgsConstructor
@RestController
@RequestMapping("/device-type")
public class DeviceTypeController {

    private final DeviceTypeService deviceTypeService;

    /**
     * 分页查询设备类型列表
     * @param currentPage 当前页码
     * @param pageSize 每页大小
     * @param deviceType 查询条件
     * @return 分页结果
     */
    @GetMapping("/page")
    @ApiOperation("分页查询设备类型列表")
    @PreAuthorize("hasAuthority('device-type:page')")
    public R<Page<DeviceType>> fetchDeviceTypePage(
            @RequestParam int currentPage,
            @RequestParam int pageSize,
            @RequestParam(required = false) String deviceType,
            @RequestParam(required = false) List<LocalDateTime> during
    ) {
        return R.ok(deviceTypeService.fetchDeviceTypePage(currentPage, pageSize, toBean(deviceType, DeviceType.class), during));
    }

    /**
     * 添加设备类型
     * @param deviceType 设备类型对象
     * @return 添加结果
     */
    @PostMapping
    @ApiOperation("添加设备类型")
    @PreAuthorize("hasAuthority('device-type:post')")
    public R<Void> postDeviceType(@RequestBody @Valid DeviceType deviceType) {
        deviceTypeService.postDeviceType(deviceType);
        return R.okMsg("添加设备类型成功");
    }

    /**
     * 更新设备类型
     * @param deviceType 设备类型对象
     * @return 更新结果
     */
    @PutMapping
    @ApiOperation("更新设备类型")
    @PreAuthorize("hasAuthority('device-type:put')")
    public R<Void> putDeviceType(@RequestBody @Valid DeviceType deviceType) {
        deviceTypeService.putDeviceType(deviceType);
        return R.okMsg("更新设备类型成功");
    }

    /**
     * 删除设备类型
     * @param id 设备类型 ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    @ApiOperation("删除设备类型")
    @PreAuthorize("hasAuthority('device-type:delete')")
    public R<Void> delDeviceType(@PathVariable Long id) {
        deviceTypeService.delDeviceType(id);
        return R.okMsg("删除设备类型成功");
    }

    /**
     * 批量删除设备类型
     * @param ids 设备类型 ID 数组
     * @return 删除结果
     */
    @DeleteMapping("/batch/delete")
    @ApiOperation("批量删除设备类型")
    @PreAuthorize("hasAuthority('device-type:batch:delete')")
    public R<Void> batchDelDeviceType(@RequestParam List<Long> ids) {
        deviceTypeService.batchDelDeviceType(ids);
        return R.okMsg("批量删除设备类型成功");
    }

    /**
     * 获取设备类型详情
     * @param id 设备类型 ID
     * @return 设备类型详情
     */
    @GetMapping("/{id}")
    @ApiOperation("获取设备类型详情")
    @PreAuthorize("hasAuthority('device-type:get')")
    public R<DeviceType> fetchDeviceTypeById(@PathVariable Long id) {
        return R.ok(deviceTypeService.fetchDeviceTypeById(id));
    }

    /**
     * 导出设备类型数据
     * @param response 响应对象
     * @throws IOException IO异常
     */
    @GetMapping("/export")
    @ApiOperation("导出设备类型数据")
    @PreAuthorize("hasAuthority('device-type:export')")
    public void exportData(HttpServletResponse response) throws IOException {
        List<DeviceType> deviceTypeList = deviceTypeService.list();
        StringBuilder csvContent = new StringBuilder();
        csvContent.append("ID,设备类型名称,系列,电流输出,端口数量,状态,创建时间,更新时间,创建用户,更新用户,是否删除\n");
        deviceTypeList.forEach(deviceType -> {
            csvContent.append(deviceType.getId()).append(",")
                    .append(deviceType.getDeviceTypeName()).append(",")
                    .append(deviceType.getSeries()).append(",")
                    .append(deviceType.getCurrentOutput()).append(",")
                    .append(deviceType.getPortCount()).append(",")
                    .append(deviceType.getStatus()).append(",")
                    .append(deviceType.getCreateTime()).append(",")
                    .append(deviceType.getUpdateTime()).append(",")
                    .append(deviceType.getCreateUser()).append(",")
                    .append(deviceType.getUpdateUser()).append(",")
                    .append(deviceType.getDeleted()).append("\n");
        });
        String filename = new SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date()) + ".csv";
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8));
        response.setContentType("application/csv");
        response.getWriter().write(csvContent.toString());
    }

    /**
     * 导入设备类型数据
     * @param file CSV文件
     * @return 导入结果
     * @throws IOException IO异常
     */
    @PostMapping("/upload")
    @ApiOperation("导入设备类型数据")
    @PreAuthorize("hasAuthority('device-type:import')")
    public R<Void> upload(@RequestParam("file") MultipartFile file) throws IOException {
//        List<DeviceType> deviceTypeList = SecurityUtil.parseCsv(file.getInputStream(), DeviceType.class);
//        deviceTypeService.saveBatch(deviceTypeList);
        return R.okMsg("导入设备类型成功");
    }

    /**
     * 分页查询设备类型列表
     * @return 分页结果
     */
    @GetMapping("/all")
    @ApiOperation("查询全部设备类型列表")
    @PreAuthorize("hasAuthority('device-type:all')")
    public R<List<DeviceType>> fetchDeviceTypeAll() {
        return R.ok(deviceTypeService.list());
    }
}

